package com.qeng.aiwanba.util;

import android.content.Context;
import android.content.Intent;
import android.os.Environment;
import android.util.Log;

import com.qeng.aiwanba.net.QYHttpUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import static com.qeng.aiwanba.util.Constants.htmlFilePath;
import static com.qeng.aiwanba.util.Constants.localHtmlVersion;

/**
 * Created by lixy on 2017/10/10.
 */

public class LocalHtmlUtil {
    private static String url = "http://api.aiwanba.com/api/misc/update";
    private static String flag = "htmlVersion";

    public static String getLocalHtml(Context context){
        int htmlVersion = getHtmlVersion(context,localHtmlVersion);
        if(htmlVersion>localHtmlVersion){
            File file = new File(htmlFilePath+File.separator+htmlVersion);
            if(file.exists()){
                return "file:///"+htmlFilePath+File.separator+htmlVersion;
            }
        }
        return "file:///android_asset/html";
    }

    public static void checkHtmlUpdate(final Context context){
        final int htmlVersion = getHtmlVersion(context,localHtmlVersion);
        Map<String,String> params = new HashMap<>();
        params.put("appVer",Util.getVersion(context));
        params.put("buildVer",String.valueOf(Util.getVersionCode(context)));
        params.put("bundleID",Util.getPackageName(context));
        params.put("htmlVersion",String.valueOf(htmlVersion));
//        params.put("ios_or_android","android");
        QYHttpUtils.doPost(context, url, params, new QYHttpUtils.RequestCallback<String>() {
            @Override
            public void success(String result) {
                try {
                    JSONObject object = new JSONObject(result).optJSONObject("data");
                    final String version = object.optString("version");
                    final String url = object.optString("url");
                    final String name = object.optString("zip_name");
                    String status = object.optString("status");
                    if(status.equals("yes")){
                        //需要更新html
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                int result = downloadHtmlZip(context,url,name);
                                if(result == 0) {
                                    //下载及解压完成后修改当前html版本号
                                    Log.e("tag","解压完成");
                                    saveHtmlVersion(context, Integer.valueOf(version));
                                    context.sendBroadcast(new Intent(Constants.BROADCAST_HTML_DOWNLOAD_FINISH));
                                }

                            }
                        }).start();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void failure(Exception e) {

            }
        });
    }


    private static int downloadHtmlZip(final Context context,String fileUrl,String fileName){
        if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
            URL url = null;
            try {
                url = new URL(fileUrl);
                HttpURLConnection conn =  (HttpURLConnection) url.openConnection();
                conn.setConnectTimeout(5*1000);
                if(conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
                    InputStream is = conn.getInputStream();
                    File rootDir = new File(Constants.htmlFilePath);
                    if(!rootDir.exists()){
                        rootDir.mkdirs();
                    }
                    File file = new File(Constants.htmlFilePath,fileName);
                    FileOutputStream fos = new FileOutputStream(file);
                    BufferedInputStream bis = new BufferedInputStream(is);
                    byte[] buffer = new byte[1024];
                    int len;
                    while ((len = bis.read(buffer)) != -1) {
                        fos.write(buffer, 0, len);
                    }
                    fos.close();
                    bis.close();
                    is.close();
                    return ZipUtils.UnZipFolder(file.getPath(),Constants.htmlFilePath);
                }
                return -1;
            }catch (Exception e) {
                e.printStackTrace();
            }
        }
        return -1;
    }


    private static void saveHtmlVersion(Context context,int version){
        SharedPreferencesUtil.setAppValue(context,flag,version);
    }

    public static int getHtmlVersion(Context context,int defaultValue){
        return (Integer)SharedPreferencesUtil.getAppValue(context,flag,defaultValue);
    }
}
